﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using tracker.Models.BLL;
using tracker.Models;
using System.Data;
using tracker.Models.DTO;

namespace tracker.Controllers
{
    public class HandlerSearchAlarmController : Controller
    {
       /// <summary>
       /// Get All Alarm Define
       /// </summary>
       /// <returns></returns>
        [CallAjaxFilter]
        public JsonStringResult Index(string speedCompare, string speedNumber, string alarmId, string fromtime, string totime, string limit, string start, string trackName)
        {

            string result = "";
            string _username = HttpContext.Session[Common.USER].ToString();
            string _language = HttpContext.Session[Common.LANGUAGE].ToString();
            string timezone = HttpContext.Session[Common.TIMEZONE].ToString();
            _language = _language == string.Empty ? "vi" : _language;

            if (alarmId == null || fromtime == null || totime == null || limit == null || start == null || trackName == null)
            {
                result = "{totalCount:0,data:[{}]}";
            }
            else
            {
                if (ClassCommon.classValidate.isDateTime(fromtime) && ClassCommon.classValidate.isDateTime(totime) 
                    && ClassCommon.classValidate.isInt(limit) && ClassCommon.classValidate.isInt(start))
                {
                    List<ETrackLog> listTrackLog = new List<ETrackLog>();
                    List<ENTTrackerName> listTrackerName = new List<ENTTrackerName>();
                    listTrackerName = HandlerSearchTrackerNameController.getListDeviceByUser(_username);

                    if (listTrackerName.Count > 0)
                    {
                        string username = "";
                        foreach (ENTTrackerName item in listTrackerName)
                        {
                            username += item.username + ",";
                        }
                        username = username.Remove(username.LastIndexOf(","));

                        int iTypeSearch = 0;

                        if (speedCompare == null)
                            iTypeSearch = 0;
                        else
                            iTypeSearch = 1;

                        DataTable dtData = null;

                        if (iTypeSearch == 0)
                            dtData = TrackLogBLL.GetRecodeBySearchAlarm(new string[]{"AlarmId",
                                                                                     "TrackName",
                                                                                     "Start",
                                                                                     "End",
                                                                                     "FromTime",
                                                                                     "ToTime",
                                                                                     "UserName"},
                                                                        new object[]{alarmId,
                                                                                     trackName,
                                                                                     int.Parse(start),
                                                                                     int.Parse(limit),
                                                                                     ClassCommon.gpsExtensionMethod.convertGMTServerTime(DateTime.Parse(fromtime),timezone),
                                                                                     ClassCommon.gpsExtensionMethod.convertGMTServerTime(DateTime.Parse(totime),timezone),
                                                                                     username}).Tables[0];
                        #region Comment
                        /*
                        else if (iTypeSearch == 1)
                        {
                            if (speedCompare == ">=")
                                listTrackLog = BTrackLog.getRecodeBySearchSpeedAlarmMoreThan(DateTime.Parse(fromtime).convertGMTServerTime(), DateTime.Parse(totime).convertGMTServerTime(), trackName, float.Parse(speedNumber), int.Parse(start), int.Parse(limit), username);
                            else
                                listTrackLog = BTrackLog.getRecodeBySearchSpeedAlarmLessThan(DateTime.Parse(fromtime).convertGMTServerTime(), DateTime.Parse(totime).convertGMTServerTime(), trackName, float.Parse(speedNumber), int.Parse(start), int.Parse(limit), username);
                        }
                        */
                        #endregion

                        if (iTypeSearch == 0)
                        {
                            if (dtData.Rows.Count > 0)
                            {
                                List<EAlarmSearch> list = new List<EAlarmSearch>();

                                foreach (DataRow item in dtData.Rows)
                                {
                                    EAlarmSearch ent = new EAlarmSearch();
                                    ent.alarmtype = int.Parse(item[EAlarmSearch._AlarmTypeID].ToString());
                                    ent.altitude = item[EAlarmSearch._Altitude].ToString();
                                    ent.direction = item[EAlarmSearch._Direction].ToString();
                                    ent.drivername = "";
                                    ent.extinfo = HandlerExcelController.getResouceByName("A" + item[EAlarmSearch._AlarmTypeID].ToString(), _language);
                                    ent.geofence_alarm_id = "14";
                                    ent.gpstime = ClassCommon.gpsExtensionMethod.convertGMTClientTime(DateTime.Parse(item[EAlarmSearch._Gps_time].ToString()),timezone).ToString("yyyy-MM-dd hh:mm:ss tt");
                                    ent.gpsvalid = item[EAlarmSearch._Gps_status].ToString().ToLower() == "valid" ? true : false;
                                    ent.gsmaccuracy = "0";
                                    ent.gsmlatitude = "0";
                                    ent.hasgsmlocation = "0";
                                    ent.latitude = item[EAlarmSearch._Latitude].ToString();
                                    // ent.location = HandlerExcel.getAddress(item[EAlarmSearch._Latitude].ToString(), item[EAlarmSearch._Longitude].ToString());
                                    ent.longitude = item[EAlarmSearch._Longitude].ToString();
                                    ent.receivedtime = ClassCommon.gpsExtensionMethod.convertGMTClientTime(DateTime.Parse(item[EAlarmSearch._RecieveTime].ToString()),timezone).ToString("yyyy-MM-dd hh:mm:ss tt");
                                    ent.RFID = "";
                                    ent.speed = item[EAlarmSearch._Speed].ToString();
                                    ent.sssid = item[EAlarmSearch._DeviceKeySecurity].ToString();
                                    ent.trackername = item[EAlarmSearch._DeviceName].ToString();

                                    list.Add(ent);
                                }
                                int iCount = 0;
                                if (iTypeSearch == 0)
                                {
                                    dtData = TrackLogBLL.GetTotalRecordBySearchAlarm(new string[]{"AlarmId",
                                                                                                  "TrackName",
                                                                                                  "Start",
                                                                                                  "End",
                                                                                                  "FromTime",
                                                                                                  "ToTime",
                                                                                                  "UserName"},
                                                                                     new object[]{alarmId,
                                                                                                  trackName,
                                                                                                  int.Parse(start),
                                                                                                  int.Parse(limit),
                                                                                                  ClassCommon.gpsExtensionMethod.convertGMTServerTime(DateTime.Parse(fromtime),timezone),
                                                                                                  ClassCommon.gpsExtensionMethod.convertGMTServerTime(DateTime.Parse(totime),timezone),
                                                                                                  username}).Tables[0];
                                    if(dtData.Rows.Count>0)
                                        iCount = int.Parse(dtData.Rows[0]["Total"].ToString());
                                }

                                dtData.Dispose();

                                if (list.Count > 0)
                                {
                                    result = Utilities.getJsonString(list, "totalCount:" + iCount.ToString() + ",data:", 1);
                                }
                                else
                                {
                                    result = "{totalCount:0,data:[]}";
                                }
                            }
                            else
                            {
                                result = "{totalCount:0,data:[]}";
                            }
                        }
                        
                        #region Comment
                        /*
                        else if (iTypeSearch == 1)
                        {
                            if (listTrackLog.Count > 0)
                            {
                                List<ELastDeviceInfo> listDeviceInfo = new List<ELastDeviceInfo>();

                                foreach (ETrackLog item in listTrackLog)
                                {
                                    ELastDeviceInfo entLastDeviceInfo = new ELastDeviceInfo();
                                    //Alarm Code

                                    entLastDeviceInfo.alarminfo = item.AlarmCode;
                                    entLastDeviceInfo.alarmlatitude = item.Latitude;
                                    entLastDeviceInfo.alarmlongitude = item.Longitude;
                                    entLastDeviceInfo.lastalarmtime = item.RecieveTime.convertGMTClientTime().ToString("yyyy-MM-dd hh:mm:ss tt");
                                    entLastDeviceInfo.alarmspeed = item.Speed;


                                    entLastDeviceInfo.altitude = item.Altitude;
                                    entLastDeviceInfo.devicename = item.DeviceName;
                                    entLastDeviceInfo.direction = item.Direction;

                                    entLastDeviceInfo.devicestate = "0";
                                    // entLastDeviceInfo.geofenceid = 100;
                                    entLastDeviceInfo.lastgeofencename = "";
                                    entLastDeviceInfo.hasgsmlocation = "";
                                    entLastDeviceInfo.RFID = "";
                                    entLastDeviceInfo.status = "";
                                    entLastDeviceInfo.gpsavailable = false;

                                    entLastDeviceInfo.runtime = item.RunTime;
                                    entLastDeviceInfo.satellites = item.Satellites;
                                    entLastDeviceInfo.gsmsignal = item.Gsm_Signal;
                                    entLastDeviceInfo.gpstime = item.Gps_time.convertGMTClientTime().ToString("yyyy-MM-dd hh:mm:ss tt");
                                    entLastDeviceInfo.HDOP = item.Hdop;
                                    entLastDeviceInfo.journey = item.Journey;
                                    entLastDeviceInfo.latitude = item.Latitude;
                                    entLastDeviceInfo.longitude = item.Longitude;
                                    entLastDeviceInfo.online = item.Gps_status;
                                    entLastDeviceInfo.receivedtime = item.RecieveTime.convertGMTClientTime().ToString("yyyy-MM-dd hh:mm:ss tt");
                                    entLastDeviceInfo.speed = item.Speed;
                                    entLastDeviceInfo.sssid = item.DeviceKeySecurity;

                                    listDeviceInfo.Add(entLastDeviceInfo);
                                }
                                int iCount = 0;

                                if (speedCompare == ">=")
                                    iCount = BTrackLog.getTotalRecordBySearchSpeedAlarmMoreThan(DateTime.Parse(fromtime).convertGMTServerTime(), DateTime.Parse(totime).convertGMTServerTime(), trackName, float.Parse(speedNumber), username);
                                else
                                    iCount = BTrackLog.getTotalRecordBySearchSpeedAlarmLessThan(DateTime.Parse(fromtime).convertGMTServerTime(), DateTime.Parse(totime).convertGMTServerTime(), trackName, float.Parse(speedNumber), username);

                                if (listDeviceInfo.Count > 0)
                                {
                                    context.Response.Write(classJavaScriptSerialize.getJsonString(listDeviceInfo, "totalCount:" + iCount.ToString() + ",data:", 1));
                                }
                                else
                                {
                                    context.Response.Write("{totalCount:0,data:[]}");
                                }
                            }
                            
                            
                            else
                            {
                                result = "{totalCount:0,data:[]}";
                            }
                        }
                        */
                        #endregion
                    }
                    else
                        result = "{totalCount:0,data:[]}";
                }
                else
                {
                    result = "{totalCount:0,data:[]}";
                }
            }
            return new JsonStringResult(result);
        }
    }
}
